package com.jjwxc.jwjskandriod.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.WebActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.model.SubscribeRequest;
import com.jjwxc.jwjskandriod.model.UserBalanceResponse;
import com.jjwxc.jwjskandriod.readActivity.ReadActivity;
import com.jjwxc.jwjskandriod.readActivity.utils.FileUtils;
import com.jjwxc.jwjskandriod.readActivity.view.TxtChapter;

import java.util.ArrayList;
import java.util.List;

public class DownMorePop {
    int pos = 0;
    int mBalance = 0;
    int price = 0;
    List<TxtChapter> mList = new ArrayList<>();
    int isNotifyData = -1;

    public void downMorePopWindow(View mView, Activity context, List<TxtChapter> list, int mNum, boolean isMonthSubscribe, DownMoreListener itemListener) {

        View view = LayoutInflater.from(context).inflate(R.layout.downmore_pop, null, false);
        List<TextView> mTextView = new ArrayList<>();
        LinearLayout ll_gmxy = view.findViewById(R.id.ll_gmxy);
        View views = view.findViewById(R.id.view);
        TextView tv_balance = view.findViewById(R.id.tv_balance);
        TextView tv_down = view.findViewById(R.id.tv_down);
        TextView tv_buy = view.findViewById(R.id.tv_buy);
        TextView tv_one = view.findViewById(R.id.tv_one);
        TextView tv_two = view.findViewById(R.id.tv_two);
        TextView tv_three = view.findViewById(R.id.tv_three);
        TextView tv_four = view.findViewById(R.id.tv_four);
        TextView tv_custom = view.findViewById(R.id.tv_custom);
        TextView tv_six = view.findViewById(R.id.tv_six);
        mTextView.add(tv_one);
        mTextView.add(tv_two);
        mTextView.add(tv_three);
        mTextView.add(tv_four);
        mTextView.add(tv_custom);
        mTextView.add(tv_six);

        if (isMonthSubscribe) {
            tv_six.setVisibility(View.VISIBLE);
        } else {
            tv_six.setVisibility(View.GONE);
        }
        //加载余额
        getBalance(tv_balance);

        tv_buy.setText("实付0完结币");

        int height = context.getResources().getDisplayMetrics().heightPixels;// 屏幕的高
        //1.构造一个PopupWindow，参数依次是加载的 View，宽高 //设置popupWindow的高为屏幕的高+顶部状态栏的高
        PopupWindow popWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT
                , height + getStatusBarHeight(context), true);
        //设置加载动画
        popWindow.setAnimationStyle(R.style.ffProg_anim);
        popWindow.setClippingEnabled(false);
        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);

        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效
        //设置 popupWindow 显示的位置，参数依次是参照 View，x轴的偏移量，y轴的偏移量
        popWindow.showAtLocation(mView, Gravity.BOTTOM, 0, 0);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                itemListener.onItemClick(isNotifyData);
            }
        });
        views.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll_gmxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(context, WebActivity.class);
                intent.putExtra("WEB_URL", Url.help4);
                intent.putExtra("WEB_NAME", "购买须知");
                context.startActivity(intent);
            }
        });
        tv_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (price > 0 && mBalance >= price) {
                    //开始批量购买
                    batchSubscribe(context, tv_balance, popWindow);
                    FFApplication.showToast("开始批量购买");
                } else {
                    new BuyWjbPop().buyWjbWindow(mView, context, price + "", value -> {
                        //更新余额
                        getBalance(tv_balance);
                    });
                }
            }
        });

        for (int i = 0; i < mTextView.size(); i++) {
            int finalI = i;
            mTextView.get(i).setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    pos = finalI;
                    for (int i = 0; i < mTextView.size(); i++) {
                        if (i == pos) {
                            mTextView.get(pos).setBackgroundResource(R.drawable.downmore_select_true);
                            mTextView.get(pos).setTextColor(Color.parseColor("#4D998D"));
                        } else {
                            mTextView.get(i).setBackgroundResource(R.drawable.downmore_select_false);
                            mTextView.get(i).setTextColor(Color.parseColor("#4E4E4E"));
                        }
                    }
                    if (finalI == 0) {//所有有权限的章节
                        price = 0;
                        tv_buy.setText("实付0完结币");
                        //清除购物车
                        mList.clear();
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).isHasAuth()) {
                                mList.add(list.get(i));
                            }
                        }
                        //开始下载免费章节
                        freeDownload(context);
                    } else if (finalI == 1) { //后30章节
                        //清除购物车
                        mList.clear();
                        int num = 0;
                        price = 0;
                        int pos = mNum;
                        if (pos < list.size()) {
                            for (int s = pos; s < list.size(); s++) {
                                if (num < 30 && !list.get(s).isHasAuth()) {
                                    num++;
                                    //计算价格
                                    price = price + Integer.parseInt(list.get(s).getPrice());
                                    //放入购物车
                                    mList.add(list.get(s));
                                }

                            }
                        }
                        tv_buy.setText("实付" + price + "完结币");
                    } else if (finalI == 2) {//后50章
                        //清除购物车
                        mList.clear();
                        int num = 0;
                        price = 0;
                        int pos = mNum;
                        if (pos < list.size()) {
                            for (int s = pos; s < list.size(); s++) {
                                if (num < 50 && !list.get(s).isHasAuth()) {
                                    num++;
                                    //计算价格
                                    price = price + Integer.parseInt(list.get(s).getPrice());
                                    //放入购物车
                                    mList.add(list.get(s));
                                }

                            }
                        }
                        tv_buy.setText("实付" + price + "完结币");
                    } else if (finalI == 3) {//后续所有的章节
                        //清除购物车
                        mList.clear();
                        price = 0;
                        int pos = mNum;
                        if (pos < list.size()) {
                            for (int s = pos; s < list.size(); s++) {
                                if (!list.get(s).isHasAuth()) {
                                    //计算价格
                                    price = price + Integer.parseInt(list.get(s).getPrice());
                                    //放入购物车
                                    mList.add(list.get(s));
                                }

                            }
                        }
                        tv_buy.setText("实付" + price + "完结币");
                    } else if (finalI == 4) {
                        //清除购物车
                        mList.clear();
                        price = 0;
                        tv_buy.setText("实付0完结币");
                        new DownCharterPop().categoryPopWindow(mView, context, list, new DownCharterPop.DownChartItemListener() {
                            @Override
                            public void onItemClick(int pos) {
                                isNotifyData = pos;
                            }
                        });
                    } else if (finalI == 5) {
                        //清除购物车
                        mList.clear();
                        price = 0;
                        tv_buy.setText("实付0完结币");
                        BuyMonthlyPop.bugMonthly(mView, context, new BuyMonthlyPop.BuyMonthPopListener() {
                            @Override
                            public void onOkClick(String group) {
                                if (group.equals("ok")) {
                                    isNotifyData = 1;
                                }
                            }
                        });

                    }

                }
            });

        }

    }

    public void batchSubscribe(Activity activity, TextView tv_balance, PopupWindow popWindow) {
        List<String> ids = new ArrayList<>();
        for (TxtChapter txtChapter : mList) {
            ids.add(txtChapter.getChapterId());
        }
        SubscribeRequest request = new SubscribeRequest();
        request.setBookId(mList.get(0).getBookId());
        request.setSubscribeType("batch");
        request.setChapterIds(ids);
        new FFNetWork().post(Url.subscribe, null, new FFNetWorkCallBack<String>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(String response) {
                if (response.contains("200")) {
                    for (int i = 0; i < mList.size(); i++) {
                        //删除未购买已经缓存的空章节
                        FileUtils.chapterCachedDelete(mList.get(i).getBookId(), mList.get(i).getChapterId());
                    }
                    ((ReadActivity) activity).mPresenter.loadChapter(mList.get(0).getBookId(), mList);
                    FFApplication.showToast("成功购买并开始下载" + mList.size() + "章节");
                    isNotifyData = 1;
                    //更新余额
                    getBalance(tv_balance);
                    popWindow.dismiss();
                }

            }

            @Override
            public boolean onFail(String response) {
                return false;
            }
        }, String.class, JSON.toJSONString(request));
    }

    /**
     * 免费章节下载
     *
     * @param activity
     */
    public void freeDownload(Activity activity) {
        ((ReadActivity) activity).mPresenter.loadChapter(mList.get(0).getBookId(), mList);
        FFApplication.showToast("成功购买并开始下载" + mList.size() + "章节");
        isNotifyData = 0;
    }

    public interface DownMoreListener {
        void onItemClick(int value);
    }

    public void getBalance(TextView textView) {
        new FFNetWork().post(Url.balance, null, new FFNetWorkCallBack<UserBalanceResponse>() {
            @Override
            public void onSuccess(UserBalanceResponse response) {
                if (response.getCode() == 200) {
                    mBalance = response.getData().getBalance();
                    textView.setText("余额" + mBalance + "完结币");
                }

            }

            @Override
            public boolean onFail(UserBalanceResponse response) {
                return false;
            }
        }, UserBalanceResponse.class);
    }

    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 状态栏高度
     */
    public int getStatusBarHeight(Context context) {
        // 获得状态栏高度
        @SuppressLint("InternalInsetResource")
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }
}
